# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2022/9/1
# @Author  : moe@miku39.fun
# @File    : Video.py
# @Software: PyCharm

import re

from bili.service.VideoAbstraction import VideoAbstraction


class Video(VideoAbstraction):
    def __init__(self, sess):
        super().__init__(sess)

    def getVideoInfo(self, video):
        url = "https://api.bilibili.com/x/web-interface/view"
        params = {video["idType"]: video["videoID"]}
        response = self.sess.get(url=url, params=params).json()
        if response["code"] == 0:
            return {
                "title": re.sub(r'[:*?"<>| ]', "-", response["data"]["title"]),
                "pages": response["data"]["pages"],
            }
        else:
            return False

    def getVideoPageInfo(self, dic):
        url = "https://api.bilibili.com/x/player/playurl"
        params = {
            self.videoBaseInfo["idType"]: self.videoBaseInfo["videoID"],  # 视频av号或bv号
            "cid": dic["cid"],  # 分P的专属ID
            "otype": "json",  # 返回结果的数据类型
            "qn": 0,  # 指定播放器的默认画质，若需大会员或画质不存在，将自行选择（无视即可）
            "fourk": 1,  # 是否允许4K视频
            "fnver": 0,  # 恒值
            "fnval": 4048,  # dash模式
        }
        response = self.sess.get(url=url, params=params).json()
        if response["code"] == 0:
            videos = []
            tempSet = []
            for each in response["data"]["dash"]["video"]:
                self.allowVideoSet.add(each["id"])  # 获取指定视频号下的所有子视频清晰度
                if each["id"] not in tempSet:
                    tempSet.append(each["id"])
                    videos.append(
                        {
                            "id": each["id"],
                            "quality": self.videoQuality.get(each["id"]),
                            "videoURLs": Video.getSourceList(each),
                        }
                    )
            audios = [
                {
                    "id": each["id"],
                    "quality": self.audioQuality.get(each["id"]),
                    "audioURLs": Video.getSourceList(each),
                }
                for each in response["data"]["dash"]["audio"]
            ]
            self.videoSourceList.append(
                {
                    "title": re.sub(
                        r'[:*?"<>| ]',
                        "-",
                        f"{dic['part']}-{dic['page']}"
                        if dic["part"] != ""
                        else f"{self.videoBaseInfo['videoID']}-{dic['page']}",
                    ),
                    "video": videos,  # 过滤相同画质视频源
                    "audio": audios,  # 音频源
                }
            )
        elif response["code"] == -412:
            print(response["message"])
            exit(1)
